package flex.cc.store.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.common.utils.DateUtil;
import flex.cc.core.utils.RequestUtil;
import flex.cc.store.dao.BookingInfoDao;
import flex.cc.store.dao.CouponTrackDao;
import flex.cc.store.dao.StoreCouponDao;
import flex.cc.store.dao.StoreInfoDao;
import flex.cc.store.dto.entity.BookingInfoEntity;
import flex.cc.store.dto.entity.CouponTrackEntity;
import flex.cc.store.dto.entity.StoreCouponEntity;
import flex.cc.store.dto.entity.StoreInfoEntity;
import flex.cc.store.dto.vo.BookingInfoVo;
import flex.cc.store.dto.vo.MsgConstant;
import flex.cc.store.dto.vo.StoreCouponVo;
import flex.cc.store.service.BookingInfoService;
import flex.cc.system.service.DictCodeService;
import flex.cc.util.SpecialRuleUtil;

/**
 * @author wkangle
 * @className BookingInfoService
 * @description 预约信息service
 * @time 2021-12-16 11:10:02
 */
@Service("bookingInfoService")
public class BookingInfoServiceImpl extends ServiceImpl<BookingInfoDao, BookingInfoEntity> implements BookingInfoService {

    @Resource
    private BookingInfoDao bookingInfoDao;
    @Resource
    private StoreInfoDao storeInfoDao;
    @Resource
    private StoreCouponDao storeCouponDao;
    @Resource
    private CouponTrackDao couponTrackDao;
    @Resource
	private DictCodeService dictCodeService;
    @Resource
	private SpecialRuleUtil specialRuleUtil;

    /**
     * @param params 查询参数
     * @return
     * @description 根据参数查询预约信息实体
     * @author wkangle
     * @time 2021-12-16 13:31:12
     * @exception/throws
     */
    @Override
    public BookingInfoVo getOneByParams(Map<String, Object> params) {
        return bookingInfoDao.getOneByParams(params);
    }

    /**
     * @param storeCouponVo 卡券
     * @return
     * @description 根据卡券信息构造预约提交页面信息
     * @author wkangle
     * @time 2021/12/16 0016 10:38
     * @exception/throws
     */
    @Override
    public BookingInfoVo openBooking(StoreCouponVo storeCouponVo) {
        BookingInfoVo bookingInfoVo = new BookingInfoVo();
        bookingInfoVo.setCarNo(storeCouponVo.getCarNo()); // 车牌号码
        bookingInfoVo.setContactPhone(storeCouponVo.getPhone()); // 联系电话
        bookingInfoVo.setOptionType(storeCouponVo.getIsBooking()); // 点重新预约时，storeCouponVo的isBooking由1改为0，以便打开的是预约提交页面
        return bookingInfoVo;
    }

    /**
     * @param bookingInfoVo 预约信息
     * @return
     * @description 根据预约信息构造预约提交页面信息（重新打开预约提交页面）
     * @author wkangle
     * @time 2021/12/16 0016 13:25
     * @exception/throws
     */
    @Override
    public BookingInfoVo reopenBooking(BookingInfoVo bookingInfoVo) {
        return null;
    }

    /**
     * @param reqVo 预约信息
     * @return
     * @description 预约提交
     * @author wkangle
     * @time 2021/12/19 0019 15:55
     * @exception/throws
     */
    @Override
    public Map<String, String> saveBooking(Map<String, Object> reqVo) {
        System.out.println("///////////////////////////////=: " + reqVo);
        Map<String, String> result = new HashMap<>();
        /**
         * 0、判断是否已经预约
         * 1、校验车牌号
         * 2、校验是否符合规则
         * 2、提交保存
         */
        String isBooking = reqVo.get("isBooking").toString(); // 是否已经预约：0-否 1-是
        Long couponId = PublicUtil.isNotEmpty(reqVo.get("id")) ? Long.valueOf(reqVo.get("id").toString()) : null;
        String carNo = PublicUtil.isNotEmpty(reqVo.get("carNo")) ? reqVo.get("carNo").toString() : null;
        String couponNum = PublicUtil.isNotEmpty(reqVo.get("couponNum")) ? reqVo.get("couponNum").toString() : null;
        String packageCode = PublicUtil.isNotEmpty(reqVo.get("packageCode")) ? reqVo.get("packageCode").toString() : null;
        Date arrivalTime = null;
        try {
            if (PublicUtil.isNotEmpty(reqVo.get("arrivalTime"))) {
                arrivalTime = DateUtil.parseStringToDate(reqVo.get("arrivalTime").toString(), "yyyy-MM-dd");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "0001");
            result.put("message", "到店日期格式有误！");
            return result;
        }
        String activityId = PublicUtil.isNotEmpty(reqVo.get("activityId")) ? reqVo.get("activityId").toString() : null;//服务类型id
        String activityName = PublicUtil.isNotEmpty(reqVo.get("activityName")) ? reqVo.get("activityName").toString() : null;//服务项目名称
        Long storeInfoId = PublicUtil.isNotEmpty(reqVo.get("storeInfoId")) ? Long.valueOf(reqVo.get("storeInfoId").toString()) : null;
        
        System.out.println("-----packageCode----"+packageCode);
        System.out.println("-----couponNum----"+couponNum);
        System.out.println("-----activityId----"+activityId);
        System.out.println("-----activityName----"+activityName);
        System.out.println("-----isBooking----"+isBooking);
        System.out.println("-----carNo----"+carNo);
        System.out.println("-----couponId----"+couponId);

        BookingInfoEntity bookingInfoEntity = new BookingInfoEntity();
        if ("1".equals(isBooking)) {
            Map<String, Object> bookingInfoParams = new HashMap<>();
            bookingInfoParams.put("couponId", couponId);
            bookingInfoEntity = bookingInfoDao.getOneByParams(bookingInfoParams);
        }
        bookingInfoEntity.setCouponId(couponId);
        bookingInfoEntity.setCarNo(carNo);
        bookingInfoEntity.setActivityId(activityId);
        bookingInfoEntity.setStoreInfoId(storeInfoId);
        bookingInfoEntity.setArrivalTime(arrivalTime);

        Map<String, Object> couponParams = new HashMap<>();
        couponParams.put("id", couponId);
        couponParams.put("carNo", carNo);
        couponParams.put("packageCode", packageCode);
        StoreCouponEntity storeCouponEntity = storeCouponDao.getOneByParams(couponParams);

        if (PublicUtil.isEmpty(storeCouponEntity)) {
            result.put("code", "0001");
            result.put("message", "请核对与绑定的车牌号是否一致！");
            return result;
        }
//        /**
//         * 临时方案：应对下游生成卡券时间问题
//         * 1.如果非洗车服务项，不做任何限制；
//         * 2.如果是洗车服务，查询字典数据，预约配置开关，0-关，1-开
//         *   2.1.配置关，不做次数控制；
//         *   2.2.配置开，判断同一服务包下，在同一自然月，只能使用一次
//         */
//        //TODO 预约开关配置,isBooking：0-新增预约，1-重新预约
//        if ("0".equals(isBooking)) {
//        	if(activityId.equals("5044") || activityName.equals("车辆外观服务") || activityId.equals("5048")){//普通洗车和精致洗车
//            	//查flex_dict_code表中预约开关配置
//        		System.out.println("-----查询flex_dict_code----");
//    			Map<String, Object> codeParams = new HashMap<String, Object>();
//    			codeParams.put("code", "bookingSwitch");
//    			codeParams.put("typeCode", "storeSwitch");
//    			DictCodeEntity codeVo = dictCodeService.getOneByParams(codeParams);
//    			if(codeVo!=null && codeVo.getValue().equals("1")){
//    				Map<String, Object> checkParams = new HashMap<>();
//    		        checkParams.put("carNo", carNo);
//    		        checkParams.put("activityId", activityId);
//    		        checkParams.put("packageCode", packageCode);
//    		        int checkCouponRule = bookingInfoDao.checkCouponRule(checkParams);
//    		        // TODO 使用规则
//    		        if (checkCouponRule >= 1) {
//    		            result.put("code", "0001");
//    		            result.put("message", "本月使用次数已达到上限，详情请查看\"使用规则\"说明");
//    		            return result;
//    		        }
//    			}
//            }else{
//            	System.out.println("-----不查询flex_dict_code----");
//            }
//        }
        
        
        /**
         * 根据提交的卡券以及车牌号获取对应服务项目的特殊规则 判断是否符合规则
         */
        //TODO 预约开关配置,isBooking：0-新增预约，1-重新预约
        if ("0".equals(isBooking)) {
        	boolean ruleResult = specialRuleUtil.judgeSpecialRule(couponNum,carNo);
        	if(!ruleResult){
	            result.put("code", "0001");
	            result.put("message", "本月使用次数已达到上限，详情请查看\"使用规则\"说明");
	            return result;
        	}
        }
        
        bookingInfoEntity.setStatus("1");
        LoginAuthDto loginUser = RequestUtil.getLoginUser();
        Date date = new Date();
        if ("0".equals(isBooking)) {
            bookingInfoEntity.setCreater(loginUser.getUserCode());
            bookingInfoEntity.setCreateTime(date);
            bookingInfoEntity.setUpdater(loginUser.getUserCode());
            bookingInfoEntity.setUpdateTime(date);
            bookingInfoEntity.setPackageCode(packageCode);
            bookingInfoDao.insert(bookingInfoEntity);
            saveTrack(storeCouponEntity, "0", MsgConstant.successBookingInsert, "1", loginUser.getUserCode());
        } else {
            bookingInfoEntity.setUpdater(loginUser.getUserCode());
            bookingInfoEntity.setUpdateTime(date);
            bookingInfoDao.updateById(bookingInfoEntity);
            saveTrack(storeCouponEntity, "0", MsgConstant.successBookingUpdate, "1", loginUser.getUserCode());
        }
        String strDate = null;
        try {
            if (PublicUtil.isNotEmpty(arrivalTime)) {
                strDate = DateUtil.getStrDate(arrivalTime, "YYYY-MM-dd");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "0001");
            result.put("message", "预约到店时间转换异常！");
            return result;
        }
        result.put("code", "0000");
        result.put("message", strDate); // 预约成功时，将预约到店时间返回前端
        return result;
    }

    private void saveTrack(StoreCouponEntity couponEntity, String trackType, String trackDesc, String result, String creater){
        Date d = new Date();
        CouponTrackEntity vo = new CouponTrackEntity(couponEntity.getId(),couponEntity.getCouponNum(),
                trackType,trackDesc,couponEntity.getStatus(),result);
        vo.setIsDelete(0);
        vo.setCreateTime(d);
        vo.setCreater(creater);
        vo.setUpdateTime(d);
        vo.setUpdater(creater);
        couponTrackDao.insert(vo);
    }

    /**
     * @param params 卡券信息
     * @return
     * @description 根据卡券信息查询预约信息
     * @author wkangle
     * @time 2021/12/16 0016 13:32
     * @exception/throws
     */
    @Override
    public BookingInfoVo bookingInfo(Map<String, Object> params) {
        System.out.println("=============================: " + params);
        // 预约实体信息
        Map<String, Object> storeCouponParams = new HashMap<>();
        storeCouponParams.put("couponId", params.get("id"));
        storeCouponParams.put("carNo", params.get("carNo"));
        storeCouponParams.put("activityId", params.get("activityId"));
        storeCouponParams.put("status", "1");
        BookingInfoVo bookingInfoVo = this.getOneByParams(storeCouponParams);

        if (bookingInfoVo != null) {
            // 卡券信息
            Map<String, Object> couponParams = new HashMap<>();
            couponParams.put("id", params.get("id"));
            StoreCouponEntity storeCouponEntity = storeCouponDao.getOneByParams(couponParams);
            bookingInfoVo.setStoreCouponEntity(storeCouponEntity);
            // 预约信息关联的门店信息
            Map<String, Object> storeInfoParams = new HashMap<>();
            System.out.println(bookingInfoVo.getStoreInfoId());
            storeInfoParams.put("id", bookingInfoVo.getStoreInfoId());
            StoreInfoEntity storeInfoEntity = storeInfoDao.getOneByParams(storeInfoParams);
            bookingInfoVo.setStoreInfoEntity(storeInfoEntity);

            bookingInfoVo.setOptionType("1"); // 1-show
            return bookingInfoVo;
        }
        return null;
    }
}
